<template>
    <!--<el-form-item :label="field.label" class="form-item-wrap">-->
    <!--单行文本、多行文本-->
    <template v-if="['text','textarea','password'].includes(field.type)">
        <el-input v-model="mValue"
                  :type="field.type"
                  :readonly="readonly"
                  :disabled="readonly ? false : field.disabled"
                  :placeholder="readonly ? '' : (field.placeholder || '请输入')"
                  validate-event
                  :formatter="field.formatter"
                  :parser="field.parser"
                  @change="handleChange"
        />
    </template>

    <!--数字-->
    <template v-if="['number'].includes(field.type)">
        <el-input v-model="mValue" type="text"
                  :readonly="readonly"
                  :disabled="readonly ? false : field.disabled"
                  :placeholder="readonly ? '' :(field.placeholder || '请输入')"
                  :formatter="(value) => {
                                   let newVal = `${value}`.replace(new RegExp(field.precision ? `/[^\\d.\\d]/` : '/[^\\d]/','g'), '');
                                   newVal = `${newVal}`.replace(new RegExp(`([-]{0,1})([0-9]{0,1})(\\d*(?:\\.\\d{0,${field.precision}})?).*$`,'g'), '$1$2$3');
                                   return newVal;}"
                  @change="handleChange"
        />
        <!--<el-input-number
                           style="width: 100%;"
                           v-model="mValue"
                           controls-position="right"
                           @change="handleChange"
                           :precision="field.precision"
                           :readonly="readonly"
                           :disabled="field.disabled"
                           :placeholder="field.placeholder || '请输入'"
                   />-->
    </template>


    <!--单选、多选-->
    <template v-if="['picklist','multiple'].includes(field.type)">
        <el-input :value="mValue || ''" v-if="readonly" readonly :placeholder="readonly ? ( field.placeholder || '请选择') : ''"></el-input>
        <el-select class="select-wrap" fit-input-width
                   v-show="!readonly"
                   no-data-text="没有数据"
                   :placeholder="readonly ? '' : (field.placeholder || '请选择')"
                   clearable
                   :filterable="field.filterable"
                   v-model="mValue"
                   :multiple="field.type === 'multiple'"
                   :disabled="field.disabled"
                   @change="handleChange"
        >
            <el-option
                    v-for="item in field.options"
                    :key="item.value"
                    :label="item[field.optionName || 'label']"
                    :value="item[field.optionId || 'value']"
            />
        </el-select>
    </template>


    <!--映射-->
    <template v-if="field.type === 'reference'">
        <m-reference
                :value="mValue"
                :entity-key="field.entityKey"
                :value-key="field.valueKey"
                @change="handleChange"
                :readonly="readonly"
                :disabled="readonly ? false : field.disabled"
                :placeholder="readonly ? '' : (field.placeholder || '请选择')"
                :cols="field.refCols"
                :url="field.refUrl"
                :param="field.refParam"
                :searchField="field.searchField"
        ></m-reference>
    </template>

    <!--日期时间-->
    <template v-if="['date','datetime','time','month','week','year','daterange'].includes(field.type)">
        <m-datepicker class="datepicker-wrap"
                      :value="mValue"
                      :type="field.type"
                      :value-format="field.dateFormat"
                      @change.self="handleChange"
                      :readonly="readonly"
                      :disabled="readonly ? false : field.disabled"
                      :placeholder="readonly ? '' : field.placeholder"
                      :time-picker="field.type === 'time'"
        />
    </template>

    <!--逻辑型单选-->
    <template v-if="field.type === 'bool'">
        <el-input :value="mValue ? '是': '否'" v-if="readonly" readonly></el-input>
        <el-switch v-model="mValue" @change="handleChange"
                   v-show="!readonly"
                   :disabled="field.disabled || readonly"/>
    </template>

    <!--复选框-->
    <template v-if="field.type === 'checkbox'">
        <el-checkbox-group v-model="mValue" @change="handleChange">
            <el-checkbox v-for="item in field.options" :label="item.id" >{{item.name}}</el-checkbox>
        </el-checkbox-group>
    </template>

    <!--单选框-->
    <template v-if="field.type === 'radio'">
        <el-radio-group v-model="mValue" @change="handleChange">
            <el-radio v-for="item in field.options" :label="item.id" >{{item.name}}</el-radio>
        </el-radio-group>
    </template>

    <!--上传图片-->
    <template v-if="field.type === 'picture'">
        <el-upload
                ref="uploadRef"
                class="pitcure-card"
                :file-list="fileList"
                :action="uploadUrl"
                :headers="{Authorization: `Bearer ${getToken()}`}"
                list-type="picture-card"
                :on-preview="onPreview"
                :on-remove="onRemove"
                :on-success="onUpload"
                :before-upload="beforeUpload"
                :limit="field.limit"
                :on-exceed="onExceed"
                :disabled="readonly || field.disabled"
        >
            <template #trigger>
                <i class="iconfont icon-tianjia"></i>
            </template>
        </el-upload>
        <el-image-viewer v-if="previewShow"
                         :url-list="previewList"
                         hide-on-click-modal
                         :initial-index="initialIndex"
                         @close="closePreview"
        ></el-image-viewer>
    </template>

    <!--</el-form-item>-->
</template>

<script setup>
    import {ref,reactive, defineProps, defineEmits,watch} from 'vue'
    import {getToken} from "../../../utils/cache";
    import {imgCompress} from "../../../utils/utils";

    import MReference from '@/components/common/Reference/Reference'
    import MDatepicker from '@/components/common/Datepicker/Datepicker'
    /*
    *  属性
    *  @param {object} field：字段信息
    *
    *  @param {string} id：组件标识
    *  @param {string} value：字段值
    *  @param {boolean} readonly：只读标识
    *  @param {function}changeFn：字段变化回调方法
    * */

    //请求ip地址
    // const path = process.env.VUE_APP_PATH,
    //   http = process.env.VUE_APP_URL
    const path = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_PATH : window.webConfig.webApiBasePath,
      http = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_URL : window.webConfig.webApiBaseUrl

    const props = defineProps(['field','id','value','readonly','changeFn']),
      emit = defineEmits(['m-change','update:value']);

    let mValue = ref([]),
      uploadUrl = http + 'api/v1/UpLoad/upload_training_materials_attachments',
      fileList = ref(null),
      previewShow = ref(false),
      previewList = reactive([]),
      initialIndex = ref(0),
      uploadRef = ref(null);

    /*
    * 监听
    * props.value：属性值变化触发修改内部数据mValue变化
    * */
    watch(() => props.value,(val)=>{
      let {type,field_id,options,optionId,optionName} = props.field;
      console.log(`item:${field_id}属性值变化：`,val);
      if (type === 'bool'){
        val = !!val;
      }
      if (type === 'picture') {
        let list = val && val.split(',') || [],
          files = [];
        list.forEach(item =>{
          let name = item.substring(item.lastIndexOf('_') +1 )
          files.push({name,url: path + item ,id: item})
        });
        fileList.value = files;
      }
      if (type === 'checkbox'){
        val = val || []
      }
      if (type === 'picklist'){
        let temp = val;
        val = '';
        options.forEach(item => {
          if (item[optionId || 'value'] === temp){
            val = item[optionName || 'label']
          }
        })
      }
      if (val !== undefined){
        mValue.value = val;
      }
    },{
      immediate: true
    })

    //上传图片
    function onUpload(res) {
      if ( res.errcode === 401 || res.root.response.errcode !== 0){
        return
      }
      let data = res.root.data.row[0];
      fileList.value = [...fileList.value,{name: data.shortName,url: path +data.url,id: data.url}];
      handleChange()
    }
    //删除图片
    function onRemove(file,files) {
      fileList.value = files;
      handleChange();
    }
    //预览图片
    function onPreview(file) {
      previewShow.value = true
      fileList.value.forEach(item => previewList.push(item.url));
      initialIndex.value = previewList.indexOf(file.url)
    }
    //关闭预览
    function closePreview() {
      previewShow.value = false;
    }
    //上传文件前，压缩文件
    function beforeUpload(file){
      return new Promise(resolve => {
        //文件超出500k压缩
        if (file.size < 512000) resolve(file)
        else imgCompress(file).then(f => resolve(f))
      })
    }
    //超出文件限制
    function onExceed(files) {
      console.log('上传超出限制',files)
      fileList.value.shift();
      uploadRef.value.handleStart(files[0])
      uploadRef.value.submit();
    }

    function handleChange(data) {
      console.log('item事件触发：',data);
      let {field_id,show_field,entityKey,valueKey,type,isBoolean,options} = props.field;
      if (type === 'number')data = Number(data);

      if (type === 'picture'){
        let files = [];
        fileList.value.forEach(item => {
          files.push(item.id);
        });
        data = files.join(',');
      }

      if (type === 'datetime' && data === ''){
        data = null
      }

      let valueObj = {[field_id]: data};

      if (type === 'reference' && valueKey) {
        valueKey.forEach(item => {
          if (typeof item === 'string')valueObj[item] = data[item] || '';
          if (typeof item === 'object') {
            let key = Object.keys(item)[0],
              value = item[key];
            valueObj[key] = data[value] || '';
          }
        })
      }

      let obj = {
        field: props.field,
        data: valueObj,
        value: data,
        oldValue: props.value
      };
      emit('m-change',valueObj,props.id);
      props.changeFn && props.changeFn(obj)
    }
</script>

<style scoped lang="less">
/*.form-item-wrap{
    margin-bottom: 10px;
}*/
.select-wrap{
    width: 100%;
}
.datepicker-wrap{
    width: 100%;
}
.pitcure-card{
    ::v-deep{
        .el-upload-list--picture-card{
            --el-upload-list-picture-card-size: 100px;
        }
        .el-upload--picture-card{
            --el-upload-picture-card-size: 100px;

        }
    }
}
</style>
